package cn.jit.ssm.web.controller.demo;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 下载Excel
 * 访问此地址，就会下载
 * @author: Cecurio
 * @create: 2017-12-15 16:15
 **/
@Controller
@RequestMapping(value = "/demo3")
public class DemoController3 {
    private static final Logger logger = LoggerFactory.getLogger(DemoController3.class);


    /**
     * 导出一张Excel表
     * @param response HttpServletResponse的实例
     * @param name 请求传递的参数
     */
    // 尝试这么访问 /demo3/excel/download?name=poi_is_very_strong
    @RequestMapping("/excel/download")
    public void exportExcel(HttpServletResponse response,String name) {
        try {
            // 创建一个Excel文件
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();

            // 新建一个工作表,默认名字为Sheet0
            HSSFSheet hssfSheet = hssfWorkbook.createSheet();
            // 继续新建一个工作表,默认名字为Sheet1
            HSSFSheet hssfSheet1 = hssfWorkbook.createSheet();

            HSSFRow firstRow = hssfSheet.createRow(0);
            HSSFCell cell00 = firstRow.createCell(0);
            cell00.setCellValue("name");

            HSSFRow secondRow = hssfSheet.createRow(1);
            HSSFCell cell10 = secondRow.createCell(0);
            HSSFCellStyle hssfCellStyle = hssfWorkbook.createCellStyle();
            HSSFFont font = hssfWorkbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 15);
            font.setColor(HSSFColor.RED.index);
            hssfCellStyle.setFont(font);
            cell10.setCellValue(name);
            cell10.setCellStyle(hssfCellStyle);

            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=template.xls");

            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            logger.info("导出成功！");
        } catch (IOException ex) {
            logger.info("导出失败！");
        }
    }

}
